package com.common.tools.util;

import java.util.Date;

import javax.annotation.PreDestroy;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.api.annontation.ServiceLog;
import com.common.api.iface.CodeNameEnumFace;
import com.common.tools.api.service.OperateLogService;
import com.common.tools.api.service.ParamService;
import com.common.tools.po.OperateLogPo;
import com.common.tools.po.ParamPo;
import com.common.util.GenerateSequenceUtil;
import com.common.web.util.RequestUtil;



/**
 * 
 * 基础业务服务工具类
 * @author  liuchao
 * @since 0.0.1
 */
@Component
@Lazy(false)
@Validated
@ServiceLog
public class BaseBusyServiceUtil {

	private static ApplicationEventPublisher s_applicationEventPublisher;
	
	private static OperateLogService s_operateLogService;
	
	private static ParamService s_paramService;
    
	public BaseBusyServiceUtil(ApplicationEventPublisher applicationEventPublisher,
			OperateLogService operateLogService,ParamService paramService) {
		s_applicationEventPublisher=applicationEventPublisher;
		s_operateLogService=operateLogService;
		s_paramService=paramService;
	}
	
	@PreDestroy
	public void destroy() throws Exception {
		s_applicationEventPublisher=null;
		s_operateLogService=null;
		s_paramService=null;
	}
	
	/**
	 * 事件发送
	 * @param event
	 */
	public static void publicsEvent(ApplicationEvent event) {
		s_applicationEventPublisher.publishEvent(event);
	}
	
	/**
	 * 添加操作记录
	 * 
	 * @param eventEnum
	 * @param sourceId
	 * @param content
	 */
	public static void addOperateLog(CodeNameEnumFace operateEnum, String relSourceId, Object content) {
		String contentStr="";
		if (content != null) {
            if (content instanceof String) {
            	contentStr = (String) content;
            } else {
            	contentStr = JSON.toJSONString(content);
            }
        }
    	String[] codeNames=new String[] {"",""};
    	try {
    		codeNames=RequestUtil.getUserCodeAndName();			
		} catch (Exception e2) {
//			e2.printStackTrace();
		}
    	OperateLogPo po=new OperateLogPo();
    	po.setId(GenerateSequenceUtil.generateSequenceNo());
    	po.setOperateCode(operateEnum.getEunmCode());
    	po.setOperateName(operateEnum.getEnumName());
    	po.setOperateContent(contentStr);
    	po.setOperateTime(new Date());
    	po.setOperateUserCode(codeNames[0]);
    	po.setRelSourceId(relSourceId);
		s_operateLogService.save(po);
	}
	
	public static ParamPo getParamObj(String paramCode) {
		ParamPo entity = new ParamPo();
		entity.setParamCode(paramCode);
		ParamPo po=s_paramService.getOne(Wrappers.lambdaQuery(entity));
		return po;
	}

}
